#!/bin/bash
# Author: Gary Locke
#
# Description:
#    - Parses netstat output and block IPs which are
#      consuming too many connections.

badGuys=()

iptInputChain=`iptables-save|awk '/^-A INPUT -j/ {print $NF}'`

[[ -z "$iptInputChain" ]] && iptInputChain=INPUT

if [[ ! "$iptInputChain" -eq "INPUT" ]];then
    read -p "Use $iptInputChain firewall chain? [Y/n]: " cont
    if [[ "$cont" =~ [Nn] ]];then
        echo "Exiting..."; exit 1
    fi
fi

while true; do

    loadAVG=`w|awk '/load/ {print $(NF-4),$(NF-3),$(NF-2),$(NF-1),$NF}'`

    clear

    result=`netstat -n|\
            awk '{print $5}'|\
            awk -F':' '{print $1}'|\
            sort -n|\
            uniq -c|\
            sort -n|\
            awk '{if ($3 ~ /^[ ]*$/ && $2 ~ /^[0-9].*[0-9]$/) {print $1"\t"$2}}'              |\
            tail -15`

    for ip in "${badGuys[@]}";do
        result=`echo "$result"|sed "s/$ip/& (blocked)/"`
    done

    echo -ne "$loadAVG\n\n"

    if [[ -z "$result" ]];then
        echo -ne "No IPs connected.\n"
    else
        echo -ne "Count\tAddress\n"
        echo -ne "$result\n"
    fi

    read -e -p "Blank to run again, 'quit' to exit, or enter bad IP: " addIp

    if [[ "$addIp" =~ "q" ]];then
        break;
    elif [[ ! -z "$addIp" ]];then
        iptables -I $iptInputChain -s $addIp -j DROP
        badGuys+=("$addIp")
    fi
done

echo

for i in `echo ${badGuys[@]}`;do
    echo $i
done

arrayLength=`echo ${#badGuys[@]}`
echo -ne "You've temporarily blocked $arrayLength IPs!\n\n"

exit
